<script setup lang="tsx">
import { Form } from '@/components/Form'
import { useForm } from '@/hooks/web/useForm'
import { reactive, watch, nextTick, PropType, ref, onBeforeUnmount } from 'vue'
import useSchema from './hooks/useSchema'
import { AllSchemas, CrudSchema, useCrudSchemas } from '@/hooks/web/useCrudSchemas'
// @ts-ignore
import { ElInput, ElButton, ElIcon, FormRules, ElMessage, ElMessageBox, ElTag } from 'element-plus'
import { CurdData, UploadItem } from '@/api/payment/types'
import { preViewDialogStore } from '@/store/modules/preViewDialog'
import { useI18n } from '@/hooks/web/useI18n'
import { getSelectListApi } from '@/api/operator'
import { getFieldEnumApi } from '@/api/payment'
import { FieldEnum } from '@/api/payment/types'
import { getListApi } from '@/api/purchase'
import { SelectedItem, useTableDialogStore } from '@/store/modules/tableDialog'
import { Dialog, TableDialog } from '@/components/Dialog'

defineOptions({
  name: 'PaymentSave'
})

const emit = defineEmits(['uploading'])

const { query } = useRoute()
const { t } = useI18n()
const props = defineProps({
  currentRow: {
    type: Object as PropType<Nullable<CurdData>>,
    default: () => null
  },
  examine: {
    type: Boolean,
    default: () => false
  },
  purchaseid: {
    type: Number,
    default: () => null
  },
  showUploadProof: {
    type: Boolean,
    default: () => false
  },
  showChoicePurchase: {
    type: Boolean,
    default: () => false
  }
})
console.log(props.examine, 77)
const operatorList = ref([])
const paymentFieldEnum = ref<FieldEnum>({}) // 根据实际数据初始化

const getOperatorList = async () => {
  const res = await getSelectListApi({})
  if (res) {
    operatorList.value = res.data.list
  }
}
getOperatorList()

const productPreViewId = 'productPreView'
const productPreViewIdStore = preViewDialogStore(productPreViewId)

const tableDialogSelectedLimit = 1
const tableDialogStoreID = 'paymentTableWrite'
const itemTitleName = 'purchase_no'

const tableDialogStore = useTableDialogStore(tableDialogStoreID)

const ProofArr = reactive<UploadItem[]>([])
const { formRegister, formMethods } = useForm()
const { setValues, getFormData, getElFormExpose } = formMethods
let proofList = reactive<Array<Record<string, any>>>([]) // 文件列表

interface Attachment {
  name: string
  url: string
  id: number
}

const attachmentArr = ref<Attachment[]>([])

const allSchemas = ref<AllSchemas>({
  formSchema: [] // 确保与接口匹配
})

if (props.showChoicePurchase) {
  setValues({
    pay_amount: query.pay_amount,
    total_amount: query.total_amount,
    paid_amount: query.paid_amount,
    pay_type: query.pay_type ? Number(query.pay_type) : 1,
    responsible: query.responsible ? Number(query.responsible) : 0
  })
}

const tableDialogCurdSchema = reactive<CrudSchema[]>([
  {
    field: 'selection',
    form: {
      hidden: true
    },
    search: {
      hidden: true
    },
    table: {
      type: 'selection'
    }
  },
  {
    field: 'id',
    label: t('purchase.id'),
    search: {
      hidden: true
    },
    table: {
      headerAlign: 'center',
      align: 'center'
    }
  },
  {
    field: 'supid',
    label: t('purchase.sup'),
    search: {
      hidden: true
    },
    table: {
      headerAlign: 'center',
      align: 'center',
      slots: {
        default: (data: any) => {
          return data.row.supid_value
        }
      }
    }
  },
  {
    field: 'purchase_no',
    label: t('purchase.purchase_no'),
    search: {
      // hidden: true
    },
    table: {
      headerAlign: 'center',
      align: 'center'
    }
  },
  {
    field: 'sales_orderno',
    label: t('purchase.sales_orderno'),
    search: {
      hidden: true
    },
    table: {
      headerAlign: 'center',
      align: 'center'
    }
  },
  {
    field: 'signatoryid',
    label: t('purchase.signatory'),
    search: {
      hidden: true
    },
    table: {
      headerAlign: 'center',
      align: 'center',
      slots: {
        default: (data: any) => {
          return data.row.signatoryid_value
        }
      }
    }
  },
  {
    field: 'pay_type',
    label: t('purchase.pay_type'),
    search: {
      hidden: true
    },
    table: {
      headerAlign: 'center',
      align: 'center',
      slots: {
        default: (data: any) => {
          return data.row.pay_type_value
        }
      }
    }
  },
  {
    field: 'pay_terms',
    label: t('purchase.pay_terms'),
    search: {
      hidden: true
    },
    table: {
      headerAlign: 'center',
      align: 'center',
      slots: {
        default: (data: any) => {
          return data.row.pay_terms_value
        }
      }
    }
  }
])

// const { crudSchemas } = useSchema(undefined, operatorList, props.examine)
// const { allSchemas } = useCrudSchemas(crudSchemas)

// 清空 store 数据
onBeforeUnmount(() => {
  tableDialogStore.reset()
})

getFieldEnumApi({ field: 'all' })
  .then((res) => {
    paymentFieldEnum.value = res.data

    const { crudSchemas } = useSchema(
      undefined,
      operatorList,
      props.examine,
      paymentFieldEnum.value,
      props.showUploadProof,
      productPreViewIdStore,
      proofList,
      ProofArr,
      tableDialogStoreID,
      tableDialogCurdSchema,
      props.showChoicePurchase,
      setValues,
      attachmentArr,
      undefined,
      uploading,
      setProofList,
      setProofListValue,
      formMethods
    )
    const { allSchemas: newSchemas } = useCrudSchemas(crudSchemas)

    // 合并新的数据，确保不改变原有数据的类型
    allSchemas.value = {
      formSchema: newSchemas.formSchema || []
    }
  })
  .catch((error) => {
    console.error('API call failed', error)
  })

const rules: FormRules = reactive({})

const setProofListValue = (obj: Record<string, any>) => {
  proofList.push(obj)
}

const setProofList = (file: Record<string, any>) => {
  proofList = proofList?.filter((item: any) => item.uid !== file.uid)
}

const submit = async () => {
  const elForm = await getElFormExpose()
  const valid = await elForm?.validate().catch((err) => {
    console.log('err', err)
  })
  if (valid) {
    // setValues({
    //   attachment: uploadList.join(',')
    // })
    if (props.purchaseid) {
      setValues({
        purchaseid: props.purchaseid
      })
    } else {
      setValues({
        purchaseid: tableDialogStore.selectedItems.map((item) => item.id).join(',')
      })
    }
    const formData = await getFormData()
    return formData
  }
}

watch(
  () => props.currentRow,
  async (currentRow) => {
    if (!currentRow) return

    if (currentRow.attachment_urls) {
      const attachmentList = currentRow.attachment_urls
      attachmentList.forEach((item: Attachment, index: number) => {
        // uploadList.push(item)
        attachmentArr.value.push({
          name: item.name,
          url: item.url,
          id: item.id
        })
      })
    }
    // if (currentRow.proof) {
    // const photoArr = currentRow.proof.split(',')
    // photoArr.forEach((item: string, index: number) => {
    //   proofList.push(item)
    //   ProofArr.push({
    //     name: `file${index}`,
    //     url: `http://${item}`,
    //     response: item
    //   })
    // })
    // }
    await nextTick()
    const selectedItems = ref<SelectedItem[]>([])
    selectedItems.value = [{ id: currentRow.id, title: currentRow.payno }]
    tableDialogStore.selectedItems = selectedItems.value
    setValues(currentRow)
  },
  {
    deep: true,
    immediate: true
  }
)

// 自动将付款金额设置为 剩余金额
const additional = (item) => {
  if (item.value[0].gap != undefined) {
    setValues({
      pay_amount: item.value[0].gap,
      total_amount: item.value[0].total_amount,
      paid_amount: item.value[0].pay_amount
    })
  }
}
const uploading = (status: boolean) => {
  emit('uploading', status)
}
defineExpose({
  submit
})
</script>

<template>
  <Dialog
    v-model="productPreViewIdStore.isPreViewVisible"
    :title="t('imageViewerDemo.imageViewer')"
    width="50%"
  >
    <img class="w-full" :src="productPreViewIdStore.src" alt="Preview Image" />
  </Dialog>

  <Form :rules="rules" @register="formRegister" :schema="allSchemas.formSchema" />

  <TableDialog
    :getListApi="(e) => getListApi({ ...e, pay_status: '0,1' })"
    :limit="tableDialogSelectedLimit"
    :tableDialogStoreID="tableDialogStoreID"
    :itemTitleName="itemTitleName"
    rowKey="id"
    :reserveSelection="true"
    @additional="additional"
  />
</template>

<style lang="less">
@import url('@/styles/global.less');
</style>
